
import Taro, { Component } from '@tarojs/taro'
import { connect } from "@tarojs/redux"
import _isEmpty from 'lodash/isEmpty'
import { View } from '@tarojs/components'
import { AtModal } from 'taro-ui'
import { EPage } from 'eft-cool-taro-ui'

import { getAddressBookList, delAddressFromBook } from '@/actions/common'

import AddressSearch from '@/components/AddressSearch'
import AddressBookItem from '@/components/AddressBookItem'
import BaseButton from '@/components/BaseButton'

import './index.scss'

@connect(({ common }) => ({
  common
}))
class AddressBook extends Component {
  config = {
    navigationBarTitleText: '地址簿',
  }

  constructor(props) {
    super(props)
    this.state = {
      word: '',
      page: 1,
      addressData: {},
      hasMore: true,
      noMore: false,
      delModal: false,
    }
  }

  componentDidMount() {
    Taro.eventCenter.trigger('ERefreshStart')
    this.getAddressList()
    Taro.eventCenter.trigger('ERefreshEnd')
  }

  componentWillReceiveProps(nextProps){
  
    const { common: { addressList }} = nextProps
    
    if(addressList.currPage === 1){
      this.setState({ addressData: addressList })
      const hasMore = addressList.currPage < addressList.totalPage
      this.setState({ hasMore, noMore: !hasMore })
    }else{
      const hasMore = addressList.currPage <= addressList.totalPage
      this.setState({ hasMore, noMore: !hasMore })
      if(hasMore){
        let dList = addressList
        dList.list = this.state.addressData.list.concat(dList.list)
        this.setState({
          addressData: dList 
        })
      }
      
    }
  }

  render() {
    const { addressData, hasMore, noMore, word, refreshStatus, delModal } = this.state
    const refresherConfig = {
      recoverTime: 300,
      refreshTime: 1000
    }
    return (
      <View className="addressbook-page">
        <View className="addressbook-search-fixed">
          <AddressSearch
            value={word}
            onChange={(val) => this.handleSearchAddress(val)}
          ></AddressSearch>
        </View>
        
        <EPage
          className='addressbook-list'
          onRefresh={this.handleRefresh}
          onLoadMore={this.handleLoadMore}
          noMore={noMore}
          hasMore={hasMore}
          // hasMoreText='loading'
          refresherConfig={refresherConfig}
          refreshStatus={refreshStatus}
        >
          {!_isEmpty(addressData) && addressData.list.map(dl => {
            
            return (<View className="item-wrapper" key={dl.id}>
              <AddressBookItem data={dl} onClick={() => this.handldClickAddressitem(dl)} onDelete={() => this.showDelAddressModal(true, dl.id)}/>
            </View>)
          })}
        </EPage>
        <View className="button-fixed">
          <View className="button-fixed-wrapper">
            <BaseButton 
              width='100%'
              type='primary'
              onClick={() => {
                Taro.removeStorageSync('map_select_city')
                Taro.navigateTo({
                  url: '/pages/addresscreate/index?type=add'
                })
              }}
            />
          </View>
        </View>
        <AtModal
          isOpened={delModal}
          cancelText='取消'
          confirmText='确认'
          onClose={() => this.showDelAddressModal(false) }
          onCancel={() => this.showDelAddressModal(false)}
          onConfirm={ this.handleDelAddres }
          content='确定要删除该地址吗？'
        />
      </View>
    )
  }

  /** 点击地址 */
  handldClickAddressitem = (dl) => {
    const type = this.$router.params.type
    const user = this.$router.params.user
    switch (type) {
      case 'select':
        const ud = {
          type: user,
          ...dl
        }
        Taro.setStorageSync(`address_info_${user}`, ud)
        break;
      case 'addselect':
        const ad = {
          type: user,
          ...dl
        }
        Taro.setStorageSync('address_addselect_info', ad)
        break;
      case 'add':
        Taro.setStorageSync('address_add_info', dl)
        break;
      case 'edit':
        Taro.setStorageSync('address_edit_info', dl)
        break;
      default:
        break;
    }
    setTimeout(() => {
      Taro.navigateBack()
    }, 200);

  }

  handleRefresh = () => {
    this.getAddressList(1)
    this.setState({
      page: 1,
      refreshStatus: 1
    })

    // 模拟请求
    setTimeout(() => {
      this.setState({
        refreshStatus: 2
      })
    }, Math.random() * 1000)
  }

  refreshLater = () => {
    setTimeout(() => {
      this.refresh()
    }, 1000)
  }

  handleLoadMore = () => {
    const { hasMore } = this.state
    if(hasMore){
      const page = this.state.page + 1
      this.setState(pre => ({ page: pre.page+1 }))
      this.getAddressList(page);
    }
  }

  handleSearchAddress = (val) => {
    this.setState({ 
      word: val
    }, () => {
      this.getAddressList(1)
    })
  }

  showDelAddressModal = (flag, aid) => {
    this.setState({ delModal: !!flag })
    if(!!flag){
      this.aid = aid
    }
  }
  /** 删除地址 */
  handleDelAddres = () => {
    const { dispatch } = this.props
    dispatch(delAddressFromBook(this.aid, (res) => {
      if(res.code >= 0){
        this.setState({ delModal: false })
        Taro.showToast({ title: '删除地址成功', icon: 'none'})
        this.getAddressList(1)
      }
    }))
  }

  getAddressList = (page=1) => {
    const { dispatch } = this.props
    const { word } = this.state
    let params = {
      page,
      limit: 10
    }
    if(word){
      params.word = word
    }
    dispatch(getAddressBookList(params))
  }
}

export default AddressBook
